package com.th.framework.security.captcha;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tuhang
 */
public class CaptchaAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
    public static final String FORM_ACCOUNT_KEY = "account";
    public static final String FORM_CAPTCHA_KEY = "captcha";

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/login-no-pass",
            "POST");

    private boolean postOnly = true;

    public CaptchaAuthenticationProcessingFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        System.out.println("CaptchaAuthenticationProcessingFilter.attemptAuthentication");
        if (this.postOnly && !"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String account = obtainAccount(request);
        account = (account != null) ? account : "";
        account = account.trim();
        String captcha = obtainCaptcha(request);
        captcha = (captcha != null) ? captcha : "";
        CaptchaAuthenticationToken authRequest = new CaptchaAuthenticationToken(account, captcha);
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        System.out.println("CaptchaAuthenticationProcessingFilter.attemptAuthentication1");
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    private String obtainAccount(HttpServletRequest request) {
        return request.getParameter(FORM_ACCOUNT_KEY);
    }

    private String obtainCaptcha(HttpServletRequest request) {
        return request.getParameter(FORM_CAPTCHA_KEY);
    }

    protected void setDetails(HttpServletRequest request, CaptchaAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}
